#coding:utf-8
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import websocket
from tornado.options import define, options
from kcalerter import operatedata
from kcalerter.operatedata import  sendmailbyuserid,searchContentCollectalert,alertbyalertrule
import json
from kcalerter.alerLogger import mylogg

define("port", default=8888, help="run on the given port", type=int)
class SendHandler(websocket.WebSocketHandler):
    
    clients = set()
    cache = []
    cache_size = 200
    userlist = []
    user_size = 100
    user = None
    
    def check_origin(self, origin):
        return True
    #聊哈肯定
    def allow_draft76(self):
        # for iOS 5.0 Safari
        return True
    
    def open(self):
        self.userid = self.get_arguments("userid")
        returnjson='{"type":"3","msg":"用户'+str((self.userid)[0])+'已连接上"}'
        SendHandler.clients.add(self)
        for c in self.clients:
                        #if c.userid == self.userid:
                        #    try:
            c.write_message(returnjson)
                        #    except Exception , e:
                        #        print e
        print str(self.userid)+"WebSocket opened"

    def on_close(self):
        userid = self.get_arguments("userid")
        print str(userid)+"WebSocket closed"
        #for user in SendHandler.clients:
        #   if user.userid == userid:
        SendHandler.clients.remove(self)
        
    @classmethod    
    def update_cache(cls, chat):
        cls.cache.append(chat)
        if len(cls.cache) > cls.cache_size:
            cls.cache = cls.cache[-cls.cache_size:]
            
    @classmethod
    #
    def on_message(self, message):
        #userid=self.get_arguments("userid")
        #解析json数据
        if not message.strip():
                returnjson='{"type":"3","msg":"你传的数据为空"}'
                for c in self.clients:
                    c.write_message(returnjson)
        else:    
            try:
                s = json.loads(message)
                ccc=0
            except Exception , e:
                returnjson='{"type":"3","msg":"你所传的数据不是规定的格式数据"}'
                #userid=self.get_arguments("userid")
                for c in self.clients:
                        c.write_message(returnjson)
                ccc=1
            if ccc==0:
                userid=s["userid"]
                typemsg=s["type"]
                #resulteaa=operatedata.searchuseremail()
                #senduseridString=getsenduseridmsg(resulteaa)
                #if not senduseridString.strip():
                #    senduseridString=',1,'
                if typemsg=='1':
                    #发送最新采集内容id提醒
                    msgreturn=s["msgreturn"]
                    returnjson='{"type":"1","msg":"'+msgreturn+'"}'
                    for c in self.clients:
                        #useriid=","+str((c.userid)[0].encode('utf-8'))+","
                        #if useriid in senduseridString:
                            c.write_message(returnjson)
                elif typemsg=='3':
                    #发送爬虫抓取错误信息
                    msgreturn=s["msgreturn"]
                    returnjson='{"type":"2","msg":"'+msgreturn+'"}'
                    for c in self.clients:
                        #useriid=","+str((c.userid)[0].encode('utf-8'))+","
                        #if useriid in senduseridString:
                            c.write_message(returnjson)

                elif typemsg=='4':
                    #新数据提醒
                    msgreturn=s["msgreturn"]
                    returnjson='{"type":"2","msg":"'+msgreturn+'"}'
                    for c in self.clients:
                        #useriid=","+str((c.userid)[0].encode('utf-8'))+","
                        #if useriid in senduseridString:
                            c.write_message(returnjson)
                else:
                    #新客户端连接websocket
                    returnjson='{"type":"3","msg":"用户'+str(userid[0])+'已连接上"}'
                    #clientslength=self.clients.__len__()
                    #发送给页面提示信息
                    for c in self.clients:
                        #if c.userid == userid:
                        c.write_message(returnjson)
class GetSparkHandler(tornado.web.RequestHandler):
    def get(self):   
        try:
            no11=self.get_argument('name','',strip=True).encode('utf-8')
            mylogg("from ckcalerter.py:spiker connect..."+no11)
            if no11.strip()=='':
                no11=''
                self.write(no11)
            else:
                s = json.loads(no11)
                #查询需要报警的内容
                emailtitle=''
                emailmsg=''
                if s["code"]==401:
                    jsonspaker='{"userid":"","type":"3","msgreturn":"'+s["message"].encode('utf-8')+'"}'
                    SendHandler.on_message(jsonspaker)
                    resultemailuser=operatedata.searchuseremail()
                    emailmsg=s['message'].encode('utf-8')
                    sendmailbyuserid(resultemailuser,emailtitle,emailmsg)
                elif  s["code"]==201:
                    jsonspaker='{"userid":"","type":"4","msgreturn":"新数据"}'
                    SendHandler.on_message(jsonspaker)
                    
                    resultreturnids=searchContentCollectalert()
                    if len(resultreturnids)>0:
                        #匹配预警规则
                        webids,email=alertbyalertrule(resultreturnids)
                        resultemailuser=operatedata.searchuseremail()
                        '''
                        infoids=''
                        for m in range(len(resultreturnids)):
                            if not infoids.strip():
                                infoids=str(resultreturnids[m])
                            else:
                                infoids=infoids+","+str(resultreturnids[m])
                        '''
                        jsonspaker='{"userid":"","type":"1","msgreturn":"'+webids+'"}'
                        SendHandler.on_message(jsonspaker)
                        sendmailbyuserid(resultemailuser,emailtitle,email)
                        self.write(webids)
                else:
                    mylogg("from ckcalerter.py:no data")
        except Exception , e:
            print e
            mylogg(e)
def maina():
        mylogg("from ckcalerter.py:start11.............")
        tornado.options.parse_command_line()
        application = tornado.web.Application([
            (r"/getspark", GetSparkHandler),
            (r"/send", SendHandler),
        ])
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(options.port)
        mylogg("from ckcalerter.py:start.............")
        tornado.ioloop.IOLoop.current().start()



if __name__ == "__main__":
    maina()
